package com.ruoyi.common.utils;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.SimpleMultipartFile;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 生成条码工具类
 */
public class BarcodeUtils {

    /**
     * 生成条形码文件
     *
     * @param msg  条形码的文本内容
     * @return
     */
    public static File generateFile(String msg,String fileName) {
        File file = new File("/"+fileName+".png");
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            generateBarCode128(msg, 10.0, 0.3, true, true, outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
       return file;
    }

    public static byte[] generateFileInMemory(String msg, String fileName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            generateBarCode128(msg, 10.0, 0.3, true, true,baos);
            baos.flush();
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate barcode image", e);
        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return baos.toByteArray();
    }


    /**
     * 生成条形码文件并上传
     *
     * @param msg 条形码的文本内容
     * @return 文件的URL
     */
    public static String generateAndUploadFile(String msg,String fileName) {
        // 生成临时文件
//        File file = generateFile(msg,fileName);
        byte[] bytes = generateFileInMemory(msg, fileName);
//        MultipartFile multipartFile = new MockMultipartFile(fileName, bytes);

//         上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String path = null;
        try {
            path = FileUploadUtils.upload(filePath, new SimpleMultipartFile(fileName + ".png", bytes));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

//        // 删除临时文件
//        boolean deleted = file.delete();
//        if (!deleted) {
//            throw new RuntimeException("文件删除失败");
//        }

        return path;
    }
    private static void deleteTempFile(File file) {
        if (file.exists()) {
            file.delete();
        }
    }
    private static MultipartFile convertToFileItem(File file) {
        try {
            byte[] content = FileUtils.readFileToByteArray(file);
            return new SimpleMultipartFile(file.getName(), content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 生成code128条形码
     *
     * @param message       要生成的文本
     * @param height        条形码的高度
     * @param width         条形码的宽度
     * @param withQuietZone 是否两边留白
     * @param hideText      隐藏可读文本
     * @param outputStream  输出流
     */
    public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) {
        Code128Bean bean = new Code128Bean();

        // 分辨率，越大条形码就越大
        int dpi = 150;

        // 设置两侧是否留白
        bean.doQuietZone(withQuietZone);

        // 设置条形码高度和宽度
        bean.setBarHeight(ObjectUtils.defaultIfNull(height, 9.0D));
        if (width != null) {
            bean.setModuleWidth(width);
        }
        // 设置文本位置（包括是否显示）
        if (hideText) {
            bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
        }
        // 设置图片类型
        String format = "image/png";
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        // 生产条形码
        bean.generateBarcode(canvas, message);
        try {
            canvas.finish();
        } catch (IOException e) {
            //ByteArrayOutputStream won't happen
        }
    }
}
